#include "loginwindow.h"
#include "dbmanager.h"
#include <QVBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QLabel>

LoginDialog::LoginDialog(QWidget* parent) : QDialog(parent) {
    setWindowTitle("登录 / 注册");
    auto lay = new QVBoxLayout(this);
    leUser = new QLineEdit; leUser->setPlaceholderText("用户名");
    lePass = new QLineEdit; lePass->setEchoMode(QLineEdit::Password);
    lePass->setPlaceholderText("密码");
    lblMsg = new QLabel;

    auto btnLogin = new QPushButton("登录");
    auto btnReg   = new QPushButton("注册");

    lay->addWidget(leUser);
    lay->addWidget(lePass);
    lay->addWidget(btnLogin);
    lay->addWidget(btnReg);
    lay->addWidget(lblMsg);

    connect(btnLogin, &QPushButton::clicked, this, &LoginDialog::onLogin);
    connect(btnReg,   &QPushButton::clicked, this, &LoginDialog::onRegister);
}

QString LoginDialog::username() const { return leUser->text(); }

void LoginDialog::onRegister() {
    QString user = leUser->text().trimmed();
    QString pass = lePass->text();
    if (user.isEmpty() || pass.isEmpty()) {
        lblMsg->setText("用户名密码不能为空");
        return;
    }

    QString sql = QString("INSERT IGNORE INTO user (username,password) VALUES ('%1','%2')")
                      .arg(user, pass);
    if (DBManager::instance().exec(sql)) {
        lblMsg->setText("注册成功，请登录");
    } else {
        lblMsg->setText("注册失败，用户已存在");
    }
}

void LoginDialog::onLogin() {
    QString user = leUser->text().trimmed();
    QString pass = lePass->text();
    if (user.isEmpty() || pass.isEmpty()) {
        lblMsg->setText("请输入用户名和密码");
        return;
    }

    // 先检查是否被禁用
    QString sql = QString("SELECT disabled, failed_count, password FROM user WHERE username='%1'").arg(user);
    MYSQL_RES* res = DBManager::instance().query(sql);
    if (!res || mysql_num_rows(res) == 0) {
        lblMsg->setText("用户不存在");
        if(res) mysql_free_result(res);
        return;
    }
    MYSQL_ROW row = mysql_fetch_row(res);
    bool disabled = row[0] && QString(row[0]) == "1";
    int failed = row[1] ? atoi(row[1]) : 0;
    QString storedpwd = row[2] ? row[2] : "";

    mysql_free_result(res);

    if (disabled) {
        lblMsg->setText("该账户已被永久禁用！");
        return;
    }

    if (pass == storedpwd) {
        // 登录成功，重置失败次数
        DBManager::instance().exec(QString("UPDATE user SET failed_count=0 WHERE username='%1'").arg(user));
        lblMsg->setText("登录成功");
        accept();
        emit loginSuccess();
    } else {
        failed++;
        if (failed >= 3) {
            DBManager::instance().exec(QString("UPDATE user SET disabled=1,failed_count=%1 WHERE username='%2'")
                                           .arg(failed).arg(user));
            lblMsg->setText("密码错误已达3次，账户已被永久禁用！");
        } else {
            DBManager::instance().exec(QString("UPDATE user SET failed_count=%1 WHERE username='%2'")
                                           .arg(failed).arg(user));
            lblMsg->setText(QString("密码错误，还剩 %1 次机会").arg(3-failed));
        }
    }
}
